using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.Material.MaterialGroup;
using ProduceBasicData.Domain.Material;
using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.Material.MaterialGroup
{
    /// <summary>
    /// 物料群组删除处理类
    /// </summary>
    public class DeleteMaterialGroupHandler : IRequestHandler<DeleteMaterialGroupCommand, ApiResult<int>>
    {
        private readonly IBaseRespository<MaterialGroupModel> materialGroupRepository;
        private readonly IMapper mapper;

        public DeleteMaterialGroupHandler(
            IBaseRespository<MaterialGroupModel> materialGroupRepository,
            IMapper mapper)
        {
            this.materialGroupRepository = materialGroupRepository;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(DeleteMaterialGroupCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 根据ID获取物料群组数据
                var materialGroup = await materialGroupRepository.GetModelAsync(request.Id);
                if (materialGroup == null)
                {
                    result.Code = ApiEnum.Failed;
                    result.Msg = "物料群组不存在";
                    return result;
                }

                // 执行软删除（标记Isdel为true）
                materialGroup.Isdel = true;
                await materialGroupRepository.Update(materialGroup);

                result.Code = ApiEnum.Success;
                result.Msg = "物料群组删除成功";
                result.Data = materialGroup.Id;
            }
            catch (Exception ex)
            {
                result.Code = ApiEnum.Failed;
                result.Msg = $"物料群组删除异常：{ex.Message}";
            }

            return result;
        }
    }
}
